
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using MauiApp.Models;
using Microsoft.Maui.Controls;
using System;
using System.Collections.Generic;
using System.Linq;

namespace MauiApp.ViewModels
{
    public partial class StudyStatsViewModel : ObservableObject
    {
        [ObservableProperty]
        private DateTime selectedTime = DateTime.Now;

        [ObservableProperty]
        private List<StudyRecordModel> allRecords = new List<StudyRecordModel>();

        [ObservableProperty]
        private List<StudyRecordModel> dailyAnalysisData = new List<StudyRecordModel>();

        [ObservableProperty]
        private List<StudyRecordModel> weeklyAnalysisData = new List<StudyRecordModel>();

        [ObservableProperty]
        private List<StudyRecordModel> yearlyAnalysisData = new List<StudyRecordModel>();

        public StudyStatsViewModel()
        {
            // 监听SelectedTime属性变化
            PropertyChanged += (sender, e) =>
            {
                if (e.PropertyName == nameof(SelectedTime))
                {
                    RefreshAllAnalysesCommand.Execute(null);
                }
            };
        }

        [RelayCommand]
        public async Task InitializeAsync()
        {
            try
            {
                // 初始化数据
                await LoadStudyStatistics();
                RefreshAllAnalyses();
            }
            catch (Exception ex)
            {
                var mainPage = Application.Current.Windows.FirstOrDefault()?.Page;
                if (mainPage != null)
                {
                    await mainPage.DisplayAlert("错误", $"初始化失败: {ex.Message}", "确定");
                }
            }
        }
        // 示例方法：加载学习统计数据
        private async Task LoadStudyStatistics()
        {
            try
            {
                // 这里应该实现从API或数据库加载数据的逻辑
                // 为了演示，添加一些模拟数据
                AllRecords = new List<StudyRecordModel>
                {
                    new StudyRecordModel { Subject = "数学", Duration = 60, Date = DateTime.Now },
                    new StudyRecordModel { Subject = "英语", Duration = 45, Date = DateTime.Now },
                    new StudyRecordModel { Subject = "编程", Duration = 90, Date = DateTime.Now },
                    new StudyRecordModel { Subject = "数学", Duration = 75, Date = DateTime.Now.AddDays(-1) },
                    new StudyRecordModel { Subject = "英语", Duration = 30, Date = DateTime.Now.AddDays(-1) }
                };
            }
            catch (Exception ex)
            {
                var mainPage = Application.Current.Windows.FirstOrDefault()?.Page;
                if (mainPage != null)
                {
                    await mainPage.DisplayAlert("错误", $"加载数据失败: {ex.Message}", "确定");
                }
            }
        }
        [RelayCommand]
        public void RefreshAllAnalyses()
        {
            RefreshDailyAnalysis();   // 日分析（饼图）
            RefreshWeeklyAnalysis();  // 周分析（堆叠柱状图）
            RefreshYearlyAnalysis();  // 年分析（堆叠柱状图）
        }

        // ---------- 日分析：选中日期的各科目时长占比（饼图） ----------
        private void RefreshDailyAnalysis()
        {
            var dailyData = from record in AllRecords
                            where record.Date.Date == SelectedTime.Date
                            group record by record.Subject into g
                            select new StudyRecordModel
                            {
                                Subject = g.Key,
                                Duration = g.Sum(r => r.Duration),
                                Date = SelectedTime.Date
                            };
            
            DailyAnalysisData = dailyData.ToList();
        }

        // ---------- 周分析：选中日期所在周，每天的科目时长堆叠（柱状图） ----------
        private void RefreshWeeklyAnalysis()
        {
            DateTime startOfWeek = SelectedTime.AddDays(-(int)SelectedTime.DayOfWeek + 1);
            DateTime endOfWeek = startOfWeek.AddDays(6);

            var weeklyData = from record in AllRecords
                             where record.Date >= startOfWeek && record.Date <= endOfWeek
                             group record by new { record.Date, record.Subject } into g
                             select new StudyRecordModel
                             {
                                 Date = g.Key.Date,
                                 Subject = g.Key.Subject,
                                 Duration = g.Sum(r => r.Duration)
                             };

            WeeklyAnalysisData.Clear();
            foreach (var item in weeklyData)
            {
                WeeklyAnalysisData.Add(item);
            }
        }

        // ---------- 年分析：选中日期所在年，每月的科目时长堆叠（柱状图） ----------
        private void RefreshYearlyAnalysis()
        {
            var yearlyData = from record in AllRecords
                             where record.Date.Year == SelectedTime.Year
                             group record by new { Month = record.Date.Month, record.Subject } into g
                             select new StudyRecordModel
                             {
                                 Date = new DateTime(SelectedTime.Year, g.Key.Month, 1),
                                 Subject = g.Key.Subject,
                                 Duration = g.Sum(r => r.Duration)
                             };

            YearlyAnalysisData.Clear();
            foreach (var item in yearlyData)
            {
                YearlyAnalysisData.Add(item);
            }
        }

    }
}
